import React, { useEffect, useState } from "react";
import ReactECharts from "echarts-for-react";
import dayjs from "dayjs";
import { getUserSignInRecordUsingGet } from "@/api/userController";
import { message, Modal } from "antd";

interface Props {}
const CalendarChart = (prop: Props) => {
    const [dataList, setDataList] = useState<number[]>([]);
    const year = new Date().getFullYear();

    const fetchDataList = async () => {
        try {
            const res = await getUserSignInRecordUsingGet({ year });
            // @ts-ignore
            setDataList(res.data || []);
        } catch (e) {
            // @ts-ignore
            message.error("获取刷题签到记录失败，" + e.message);
        }
    };

    useEffect(() => {
        fetchDataList();
    }, []);

    const optionsData = dataList.map((dayOfYear) => {
        const dateStr = dayjs(`${year}-01-01`)
            .add(dayOfYear - 1, "day")
            .format("YYYY-MM-DD");
        return [dateStr, 1];
    });

    const options = {
        tooltip: {
            trigger: "item",
            formatter: (params: any) => {
                return `${params.value[0]}<br/>${params.value[1] === 1 ? "已签到 ✅" : "未签到 ❌"}`;
            },
            backgroundColor: "rgba(50,50,50,0.85)",
            textStyle: { color: "#fff" }
        },
        visualMap: {
            show: false,
            min: 0,
            max: 1,
            inRange: {
                color: ["#e0f2e9", "#24b47e"], // 从浅绿到深绿
            },
        },
        calendar: {
            range: year,
            left: 25,
            cellSize: ["auto", 18],
            splitLine: {
                lineStyle: { color: "#ccc", width: 1 },
            },
            yearLabel: {
                position: "top",
                formatter: `${year} 年刷题记录`,
                color: "#333",
                fontSize: 18,
                fontWeight: "bold",
            },
            monthLabel: {
                color: "#666",
                fontSize: 14,
            },
            dayLabel: {
                color: "#999",
            },
        },
        series: {
            type: "heatmap",
            coordinateSystem: "calendar",
            data: optionsData,
        },
    };

    const onChartClick = (params: any) => {
        Modal.info({
            title: params.value[0] + " 的签到详情",
            content: params.value[1] === 1 ? "这一天已完成签到打卡" : "这一天没有签到记录",
        });
    };

    return (
        <ReactECharts
            className="calendar-center"
            option={options}
            onEvents={{ click: onChartClick }}
        />
    );
};

export default CalendarChart;